#include<iostream>
#include<thread> 
#include<mutex>
#include<queue>
#include<condition_variable>
#include<functional>
using namespace std;

class ThreadPool
{
public:
    ThreadPool(int num) :stop(false) {  
        for (int i = 0; i < num; i++)
        {
            threads.emplace_back([this] {
                while (true)
                {
                    unique_lock<mutex> lock(mut);
                    condition.wait(lock, [this] {return stop || !tasks.empty(); });
                    if (stop && tasks.empty()) return;
                    function<void()> task(move(tasks.front()));
                    tasks.pop();
                    lock.unlock();
                    task();
                }
                });
        }
    }

    ~ThreadPool() {
        {
            unique_lock<mutex> lock(mut);
            stop = true;
        }
        condition.notify_all();
        for (thread& thread : threads)
        {
            thread.join();
        }
    }

    template<class F, class...Args>
    void enqueue(F&& f, Args&&...args)
    {
        function<void()> task(bind(forward<F>(f), forward<Args>(args)...));
        {
            unique_lock<mutex> lock(mut);  
            tasks.push(task);  
        }
        condition.notify_one();
    }

private:
    vector<thread> threads;
    queue<function<void()>> tasks;  
    mutex mut;
    condition_variable condition;
    bool stop;
};


void print_message(const string& msg) {
    cout << "Message: " << msg << " (thread: " << this_thread::get_id() << ")" << endl;
}

int main() {
    // 创建包含2个工作线程的线程池
    ThreadPool th(2);

    // 提交带参数的函数任务
    th.enqueue(print_message, "Hello World");

    // 提交Lambda表达式任务
    th.enqueue([]() {
        cout << "Hello from Lambda (thread: " << this_thread::get_id() << ")" << endl;
        });

    // 等待所有任务完成（实际应用中可能需要更复杂的同步机制）
    this_thread::sleep_for(chrono::seconds(1));

    return 0;
}

